// The version of the cache.
const VERSION = "v1.4";

// The name of the cache
const CACHE_NAME = `period-tracker-${VERSION}`;

// The static resources that the app needs to function.
const APP_STATIC_RESOURCES = [
  "/",
  "/index.html",
  "/app.js",
  "/style.css",
  "manifest.json",
  "/icons/icon1.svg",
  "/icons/icon2.svg",
  "/icons/icon3.svg",
  "/icons/icon4.svg",
];

// On install, cache the static resources
self.addEventListener("install", (event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE_NAME);
      cache.addAll(APP_STATIC_RESOURCES);
    })(),
  );
});

// delete old caches on activate
self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      const names = await caches.keys();
      await Promise.all(
        names.map((name) => {
          if (name !== CACHE_NAME) {
            return caches.delete(name);
          }
          return undefined;
        }),
      );
      await clients.claim();
    })(),
  );
});
// On fetch, intercept server requests
// and respond with cached responses instead of going to network
// self.addEventListener("fetch", (event) => {
//   // As a single page app, direct app to always go to cached home page.
//   if (event.request.mode === "navigate") {
//     event.respondWith(caches.match("/"));
//     return;
//   }
// });
// self.addEventListener('fetch', (event) => {
//   // 所有请求都从缓存获取
//   event.respondWith(caches.match(event.request));
// });
// 获取事件：拦截网络请求
self.addEventListener('fetch', event => {
  // 只处理同源请求
  if (new URL(event.request.url).origin !== self.origin) return;
  
  event.respondWith(
    caches.match(event.request)
      .then(cachedResponse => {
        // 如果缓存存在，直接返回
        if (cachedResponse) return cachedResponse;
        
        // 否则从网络获取
        return fetch(event.request);
      })
  );
});
